﻿using HDSmartCommunity.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HDSmartCommunity.WebSockets
{
    public static class SocketProcess
    {
        public static async Task<bool> PushMessage(ElevatorStatusInfo elevatorStatusInfo)
        {
            string Msg = JsonConvert.SerializeObject(elevatorStatusInfo);
            await SendMessage(Msg);
            return false;
        }

        public static async Task SendMessage(string Message)
        {
            List<WebSocket> web = ElevatorWebSocketMiddleware._sockets;

            if (web != null)
            {
                foreach (var item in web)
                {
                    try
                    {
                        if (item.State.ToString() == "Closed")
                        {
                            ElevatorWebSocketMiddleware.RemoveSocket(item);
                            //LogHelper.Log("socket断开");
                        }
                        else
                        {
                            byte[] bMessage = Encoding.UTF8.GetBytes(Message);
                            await item.SendAsync(new ArraySegment<byte>(bMessage), WebSocketMessageType.Text, true, new CancellationToken());
                        }
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
            }

        }
    }
}
